import json
from django.shortcuts import render
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.decorators import login_required

from accounts.models import Profile


# Create your views here.
@login_required()
def profile(request):
    if request.method == 'GET':
        try:
            _data = Profile.objects.get(user=request.user)
        except ObjectDoesNotExist:
            Profile.objects.create(user=request.user)
            _data = Profile.objects.get(user=request.user)

        return render(request, 'accounts/profile.html', {'data': _data})

    if request.method == 'POST':
        print(request.body.decode('utf-8'))

        postdata = {}
        for key, value in json.loads(request.body.decode('utf-8')).items():
            if key != 'csrfmiddlewaretoken':
                postdata[key] = value if value != '' else None

        try:
            _t = Profile.objects.get(user=request.user)
            _t.__dict__.update(**postdata)
            _t.save()

            return JsonResponse({'state': 1, 'message': '更新成功!'})
        except Exception as e:
            return JsonResponse({'state': 0, 'message': 'Update Error: ' + str(e)})
